const fs = require('fs').promises;
const path = require('path');

class BatchRenameDirectories {
  // 生成新的文件夹名称
  static generateNewFolderName(oldFolderName) {
    let replacements = [
      { pattern: '多图下载｜', replacement: '' },
      { pattern: /[，？?…！~_♥!「」]/g, replacement: '' }, // 匹配多个标点符号
      { pattern: /《.*?》/g, replacement: '' },   // 匹配书名号及内容
      { pattern: /_-_/gi, replacement: '' },      // 匹配特殊符号
      { pattern: '話', replacement: '话' },       // 替换单个字符
      { pattern: '未删减版全集免費在线阅读', replacement: '' },
      { pattern: '未删减版免費阅读', replacement: '' },
      { pattern: '禁漫城', replacement: '' },
      { pattern: '18禁漫画天堂', replacement: '' },
      { pattern: '色漫谷', replacement: '' },
      { pattern: '---', replacement: '' },
      { pattern: '...', replacement: '' },
      { pattern: '--', replacement: '' },
    ];
    return replacements.reduce((name, { pattern, replacement }) => {
      return name.replace(pattern, replacement);
    }, oldFolderName);
  }

  // 批量重命名目录
  static async batchRenameDirectories(baseDir) {
    try {
      // 读取指定目录的内容
      let items = await fs.readdir(baseDir, { withFileTypes: true });
      let logs = [];
      let total = 0;
      let success = 0;

      for (let item of items) {
        // 检查是否为目录
        if (item.isDirectory()) {
          total++;
          // 构造旧文件夹路径
          let oldPath = path.join(baseDir, item.name);
          // 使用generateNewFolderName函数生成新的文件夹名称
          let newName = this.generateNewFolderName(item.name);
          let newPath = path.join(baseDir, newName);
          // 如果新旧名称不同，则进行重命名
          if (newName !== item.name) {
            try {
              await fs.rename(oldPath, newPath);
              logs.push(`文件夹 "${item.name}" 已成功重命名为 "${newName}"`);
              success++;
            } catch (error) {
              logs.push(`文件夹 "${item.name}" 重命名失败: ${error.message}`);
            }
          } else {
            logs.push(`文件夹 "${item.name}" 无需重命名`);
          }
        }
      }

      return {
        total,
        success,
        logs
      };
    } catch (error) {
      throw new Error(`批量重命名目录失败: ${error.message}`);
    }
  }
}

module.exports = BatchRenameDirectories;